package com.linewow.xhyy.nihaonew.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by LXR on 2016/8/22.
 * 字符串 和图片读取写入工具类
 */
public class FileUtil {
    private Context context;
    private String path;

    public FileUtil(Context context) {
        this.context = context;
        this.path=CommonUtil.getPhotoPath(context);
    }

    public void writeBitmap(Bitmap bitmap, String name){
        File file=new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        try {
            FileOutputStream fos=new FileOutputStream(path+name);
            ByteArrayOutputStream bos=new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,bos);
            fos.write(bos.toByteArray());
            fos.flush();
            fos.close();
            bos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Bitmap readBitmap(String name){
        Bitmap bitmap=null;
        bitmap= BitmapFactory.decodeFile(path+name);
        return bitmap;
    }

    public void writeStringValue(String name,String value){
        File file=new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        try {
            FileOutputStream fos=new FileOutputStream(path+name);
            fos.write(value.getBytes());
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String readStringValue(String name){
        String value=null;
        try {
            FileInputStream fis=new FileInputStream(path+name);
            BufferedReader br=new BufferedReader(new InputStreamReader(fis));
            StringBuilder sb=new StringBuilder();
            String line;
            while((line=br.readLine())!=null){
                sb.append(line);
            }
            br.close();
            fis.close();
            value=sb.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return value;
    }


    //SD卡判断->sd卡挂载返回true反之返回false
    private boolean IsSDCard(){
        boolean flag = false;
        String state = Environment.getExternalStorageState();
        if(state.equals(Environment.MEDIA_MOUNTED)){
            flag = true;
            return flag;
        }
        return flag;
    }
}
